package cheeese.and.crackers;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.TextView;

/**
 * Task View Activity Class
 * @author Cheese and Crackers
 *
 */
public class TaskViewActivity extends Activity{
	
	private UserList users;
	private User activeUser;
	private Button addTaskButton;
	private Button logoutButton;
	private ListView list;
	private Filter filter;
	private Spinner categorySpinner;
	private CheckBox incompleteOnly;
	private CheckBox afterDateBox;
	private EditText dateText;
	
	/** 
	 * Called when the activity is first created. 
     * 
     * @param savedInstanceSate Saved state of activity when last suspended
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.taskviewscreen);
        
        addTaskButton = (Button)findViewById(R.id.buttonAddTask);
        logoutButton = (Button)findViewById(R.id.buttonLogout);
        TaskViewClickListener myListener = new TaskViewClickListener();
        addTaskButton.setOnClickListener(myListener);
        logoutButton.setOnClickListener(myListener);
        filter = new Filter(null, null, null);
        
        categorySpinner = (Spinner) findViewById(R.id.spinnerCategory);
 		
 		String[] categories = {"All", "Personal", "School", "Work"};
 		
 		ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
 		
 		categorySpinner.setAdapter(categoryAdapter);
 		categorySpinner.setOnItemSelectedListener(new CategoryListener());
 		
 		incompleteOnly = (CheckBox) findViewById(R.id.checkBoxIncompleteOnly);
 		incompleteOnly.setOnClickListener(myListener);
 		
 		afterDateBox = (CheckBox) findViewById(R.id.checkBoxAfterDate);
 		afterDateBox.setOnClickListener(myListener);
 		
 		dateText = (EditText)findViewById(R.id.editTextAfterDate);
 		dateText.addTextChangedListener(new DateTextWatcher());
    }
     
     /**
      * Method to call when activity is resumed
      */
     @Override
     public void onResume(){
    	 super.onResume();
    	 users = new UserList();
         try {
 			users.load(getApplicationContext());
 		} catch (Exception e) {
 			Toast.makeText(getApplicationContext(), (CharSequence)("Fatal Error With User Storage - Shutting Down"), Toast.LENGTH_SHORT).show();
     		try {
     			Thread.sleep(2000);
     		} 
     		catch(InterruptedException e2) {} 
     		android.os.Process.killProcess(android.os.Process.myPid());
 		}
    	//Get Active User
 		Bundle activeUserBundle = this.getIntent().getExtras();
 		String activeUserString = activeUserBundle.getString("ACTIVE_USER");
 		activeUser = users.getUser(activeUserString);
 		//Populate List view HERE!!!
 		list = (ListView) findViewById(R.id.listViewTasks);
 		
 		repopulate();
 		
 		TaskViewListListener listListener = new TaskViewListListener();
 		list.setOnItemClickListener(listListener);
     }
     
     /**
      * Re-populates list
      */
     private void repopulate(){
    	 String[] taskStrings = activeUser.getTasks().getStringTasks(filter);
  		//Edit list based on filters here
  		ArrayAdapter<String> taskAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, taskStrings);
  		
  		list.setAdapter(taskAdapter);
     }
     
     /**
      * Method to call when activity is paused
      */
      @Override
      public void onPause(){
  	   super.onPause();
      	try{
      		users.save(getApplicationContext());
      	}
      	catch(Exception e){
      		Toast.makeText(getApplicationContext(), (CharSequence)("Fatal Error With User Storage - Shutting Down"), Toast.LENGTH_SHORT).show();
      		try {
      			Thread.sleep(2000);
      		} 
      		catch(InterruptedException e2) {} 
      		android.os.Process.killProcess(android.os.Process.myPid());
      	}
      }
     
     /**
      * Listener for button
      */
     public class TaskViewClickListener implements OnClickListener {
     	@Override
     	/**
     	 * Checks which button was pressed and takes appropriate action, login or create user
     	 * @param v The view which was clicked
     	 */
 		public void onClick(View v) {
     		if(v==addTaskButton){
     			Intent addTaskIntent = new Intent(v.getContext(), NewTaskActivity.class);
     			addTaskIntent.putExtra("ACTIVE_USER", activeUser.getLoginId());
     			startActivity(addTaskIntent);
     		}
     		else if(v==logoutButton){
     			finish();
     		}
     		else if(v==incompleteOnly){
     			filter.setComplete(!incompleteOnly.isChecked());
     			repopulate();
     		}
     		else if(v==afterDateBox){
     			String date = (dateText.getText().toString());
     			if(date.equals("") || (!afterDateBox.isChecked())){
     				filter.setStartDate(null);
     			}
     			else{
     				filter.setStartDate(date);
     			}
     			repopulate();
     		}
     	}
     }  
     
     /**
      * Listener for list
      */
     public class TaskViewListListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
			Intent individualTaskViewIntent = new Intent(v.getContext(),IndividualTaskViewActivity.class);
			individualTaskViewIntent.putExtra("ACTIVE_USER", activeUser.getLoginId());
			individualTaskViewIntent.putExtra("ACTIVE_TASK", ((TextView)v).getText());
			
			startActivity(individualTaskViewIntent);
		}
     }
     
     /**
      * Listener for Category Spinner
      */
     public class CategoryListener implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
			String category = parent.getItemAtPosition(pos).toString();
			if(category == "All"){
				filter.setType(null);
			}
			else{
				filter.setType(category);
			}
			repopulate();
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			//Do nothing
		}
    	 
     }
     
     /**
      * Watcher for Date Text
      */
     public class DateTextWatcher implements TextWatcher{

		@Override
		public void afterTextChanged(Editable arg0) {
			String date = (dateText.getText().toString());
 			if(date.equals("") || (!afterDateBox.isChecked())){
 				filter.setStartDate(null);
 			}
 			else{
 				filter.setStartDate(date);
 			}
 			repopulate();
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			//Do Nothing
		}

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			//Do Nothing
		}
    	 
     }
}
